﻿#include "CustomTableWidget.h"
#include "TableLineEdit.h"
#include "TableCheckBox.h"

#include <QHeaderView>
#include <QPushButton>
#include <QHBoxLayout>
#include <QDebug>


CustomTableWidget::CustomTableWidget(QWidget *parent)
    : FTableWidget(parent)
    , m_checkBoxColumnWidth(10)
    , m_buttonColumnWidth(50)
    , m_isAllChecked(false)
    , m_keyEnterCallButton(false)
{
    // 禁用选择
    setSelectionMode(QAbstractItemView::NoSelection);
    setSelectionBehavior(QAbstractItemView::SelectRows);

    // 设置表头样式
    horizontalHeader()->setSectionsClickable(true);  // 表头可点击
    horizontalHeader()->setHighlightSections(true);  // 表头高亮

    // 固定行高
    verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);
    verticalHeader()->setDefaultSectionSize(32);

    // 设置垂直表头不可见
    verticalHeader()->setVisible(false);

    setShowGrid(false);

    // 相邻行颜色交替
    setAlternatingRowColors(true);

    // 设置第一列（复选框列）的对齐方式
    horizontalHeader()->setDefaultAlignment(Qt::AlignRight);

    connect(horizontalHeader(), &QHeaderView::sectionClicked, this, &CustomTableWidget::onHeaderSectionClicked);
}

void CustomTableWidget::setupColumns()
{
    if (m_headers.isEmpty()) return;

    setColumnCount(m_headers.size());
    setHorizontalHeaderLabels(m_headers);

    // 设置第一列（复选框列）宽度固定且不可调整
    horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
    setColumnWidth(0, m_checkBoxColumnWidth);

    // 设置最后一列（按钮列）宽度固定
    horizontalHeader()->setSectionResizeMode(columnCount()-1, QHeaderView::ResizeToContents);
    // setColumnWidth(columnCount()-1, m_buttonColumnWidth);

    // 其他列可调整宽度
    for(int i = 1; i < columnCount()-1; ++i) {
        horizontalHeader()->setSectionResizeMode(i, QHeaderView::Interactive);
        setColumnWidth(i, 150);
    }

    // 表头居中
    for (int i = 0; i < columnCount(); i++) {
        horizontalHeaderItem(i)->setTextAlignment(Qt::AlignCenter);
    }
}

void CustomTableWidget::updateColumnAlignment(int column)
{
    // 更新已存在的所有行的对齐方式
    for (int row = 0; row < rowCount(); ++row) {
        if (QTableWidgetItem* item = this->item(row, column)) {
            item->setTextAlignment(m_columnAlignments[column]);
        }
    }
}

void CustomTableWidget::setupRowData(int row, const QStringList& data)
{
    // 添加复选框
    TableCheckBox* checkBox = new TableCheckBox(this);
    setCellWidget(row, 0, checkBox);
    connect(checkBox, &TableCheckBox::stateChanged, this, [this, row](int state) {
        emit checkBoxClicked(row, state == Qt::Checked);
    });

    // 添加数据
    for(int i = 0; i < data.size() && i < columnCount()-2; ++i) {
        TableLineEdit* edit = new TableLineEdit(data[i], this);

        // 使用存储的对齐方式，如果没有设置则默认居中
        Qt::Alignment alignment = m_columnAlignments.value(i + 1, Qt::AlignCenter);
        edit->setAlignment(alignment);

        setCellWidget(row, i+1, edit);

        // 连接焦点移动信号
        connect(edit, &TableLineEdit::focusMoveRequest, this, [=](TableLineEdit::Direction direction){
            int realRow = getEditRow(edit);
            if (realRow >= 0) moveFocus(realRow, i+1, direction);
        });

        // 连接回车键信号
        connect(edit, &TableLineEdit::keyEnterRequest, this, [=](){
            if (m_keyEnterCallButton) {
                int realRow = getEditRow(edit);
                if (realRow >= 0) emit buttonClicked(realRow);
            }
        });
    }
}

int CustomTableWidget::getEditRow(TableLineEdit *edit)
{
    for (int row = 0; row < rowCount(); row++) {
        for (int col = 1; col < columnCount() - 1; col++) {
            TableLineEdit* current = qobject_cast<TableLineEdit*>(cellWidget(row, col));
            if (edit == current) return row;
        }
    }
    return -1;
}

int CustomTableWidget::getBtnRow(QAbstractButton *btn)
{
    if (columnCount() <= 2) return -1;
    for (int row = 0; row < rowCount(); row++) {
        QAbstractButton* current = qobject_cast<QAbstractButton*>(cellWidget(row, columnCount() - 1));
        if (btn == current) return row;
    }
    return -1;
}

void CustomTableWidget::onHeaderSectionClicked(int logicalIndex)
{
    // 只处理第一列（复选框列）的点击
    if (logicalIndex != 0) return;

    // 切换全选状态
    m_isAllChecked = !m_isAllChecked;

    // 更新所有行的复选框状态
    for(int row = 0; row < rowCount(); ++row) {
        if(TableCheckBox* cb = qobject_cast<TableCheckBox*>(cellWidget(row, 0))) {
            cb->setChecked(m_isAllChecked);
        }
    }
}

void CustomTableWidget::moveFocus(int row, int col, TableLineEdit::Direction direction)
{
    int newRow = row;
    int newCol = col;

    switch(direction) {
    case TableLineEdit::Top: // 上
        if (row > 0) newRow--;
        break;
    case TableLineEdit::Bottom: // 下
        if (row < rowCount()-1) newRow++;
        break;
    case TableLineEdit::Left: // 左
        if (col > 1) newCol--; // 避开复选框列0
        break;
    case TableLineEdit::Right: // 右
        if (col < columnCount()-2) newCol++; // 避开按钮列
        break;
    }

    QWidget* w = cellWidget(newRow, newCol);
    if (w) {
        w->setFocus();
//        if (auto le = qobject_cast<QLineEdit*>(w)) {
//            le->selectAll(); // 焦点后全选，用户体验更好
//        }
    }
}

void CustomTableWidget::setHeaders(const QStringList& headers)
{
    m_headers = headers;
    if (!m_headers.at(0).isEmpty()) {
        m_headers.push_front("");
    }
    setupColumns();
}

void CustomTableWidget::setCustomColumnWidth(int column, int width)
{
    if (column < 0 || column >= columnCount()) return;

    if (column == 0) {
        // m_checkBoxColumnWidth = width;
        return;
    } else if (column == columnCount() - 1) {
        m_buttonColumnWidth = width;
    }

    setColumnWidth(column, width);
}

void CustomTableWidget::setColumnAlignment(int column, Qt::Alignment alignment)
{
    if (column < 0 || column >= columnCount()) return;
    m_columnAlignments[column] = alignment;
    updateColumnAlignment(column);
}

int CustomTableWidget::checkedRowsCount() const
{
    int cnt = 0;
    for (int i = 0; i < rowCount(); i++) {
        if (isRowChecked(i)) cnt++;
    }
    return cnt;
}

bool CustomTableWidget::isRowChecked(int row) const
{
    if (row < 0 || row >= rowCount()) return false;
    TableCheckBox* box = qobject_cast<TableCheckBox*>(cellWidget(row, 0));
    if (box) return box->isChecked();
    else return false;
}

QString CustomTableWidget::cellText(int row, int col) const
{
    if (row < 0 || row >= rowCount()) return "";
    if (col < 1 || col >= columnCount() - 1) return "";
    TableLineEdit* edit = qobject_cast<TableLineEdit*>(cellWidget(row, col));
    return edit->text();
}

void CustomTableWidget::setCellText(int row, int col, const QString& text)
{
    if (row < 0 || row >= rowCount()) return;
    if (col < 1 || col >= columnCount() - 1) return;
    TableLineEdit* edit = qobject_cast<TableLineEdit*>(cellWidget(row, col));
    edit->setText(text);
}

void CustomTableWidget::setCellValidator(int row, int col, QRegExpValidator *validator)
{
    if (row < 0 || row >= rowCount()) return;
    if (col < 1 || col >= columnCount() - 1) return;
    TableLineEdit* edit = qobject_cast<TableLineEdit*>(cellWidget(row, col));
    edit->setValidator(validator);
}

void CustomTableWidget::setCellPasteCallback(int row, int col, QStringCallback_fn callback)
{
    if (row < 0 || row >= rowCount()) return;
    if (col < 1 || col >= columnCount() - 1) return;
    TableLineEdit* edit = qobject_cast<TableLineEdit*>(cellWidget(row, col));
    edit->setPasteCallback(callback);
}

void CustomTableWidget::setCellAutoComplete(int row, int col, const QStringList &displays, const QStringList &values)
{
    if (row < 0 || row >= rowCount()) return;
    if (col < 1 || col >= columnCount() - 1) return;
    TableLineEdit* edit = qobject_cast<TableLineEdit*>(cellWidget(row, col));
    edit->setAutoComplete(displays, values);
}

void CustomTableWidget::enableCellAutoComplete(int row, int col, bool en)
{
    if (row < 0 || row >= rowCount()) return;
    if (col < 1 || col >= columnCount() - 1) return;
    TableLineEdit* edit = qobject_cast<TableLineEdit*>(cellWidget(row, col));
    edit->enableAutoComplete(en);
}

void CustomTableWidget::enableCellKeyEnterCallButton(bool en)
{
    m_keyEnterCallButton = en;
}

void CustomTableWidget::addRow(const QStringList& data, const QString& buttonText)
{
    insertRow(rowCount(), data, buttonText);
}

void CustomTableWidget::addRow(const QStringList& data, QAbstractButton* btn)
{
    insertRow(rowCount(), data, btn);
}

void CustomTableWidget::insertRow(int row, const QStringList &data, const QString &buttonText)
{
    QTableWidget::insertRow(row);

    setupRowData(row, data);

    if (!buttonText.isEmpty()) {
        // 添加默认按钮
        QPushButton* button = new QPushButton(buttonText, this);
        setCellWidget(row, columnCount()-1, button);
        connect(button, &QPushButton::clicked, this, [=]() {
            int realRow = getBtnRow(button);
            if (realRow >= 0) emit buttonClicked(realRow);
        });
    }
}

void CustomTableWidget::insertRow(int row, const QStringList &data, QAbstractButton *btn)
{
    if (!btn) return;  // 空指针检查

    QTableWidget::insertRow(row);

    setupRowData(row, data);

    // 设置自定义按钮的父对象
    btn->setParent(this);

    // 添加自定义按钮
    setCellWidget(row, columnCount()-1, btn);

    // 连接按钮信号
    connect(btn, &QAbstractButton::clicked, this, [=]() {
        int realRow = getBtnRow(btn);
        if (realRow >= 0) emit buttonClicked(realRow);
    });
}

void CustomTableWidget::setButtonText(int row, const QString& text)
{
    if (row < 0 || row >= rowCount()) return;

    if (QPushButton* button = qobject_cast<QPushButton*>(cellWidget(row, columnCount()-1))) {
        button->setText(text);
    }
}
